/**
 *
 */
package com.thinkdit.lib.util;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.Uri;

import org.json.JSONException;

import java.io.File;
import java.security.MessageDigest;
import java.util.List;

/**
 * @author QiuDa
 */
public class PackageUtil {
    private static final String TAG = "PackageUtil";

    /**
     * 获取versioncode
     *
     * @param context
     * @return
     * @throws JSONException
     */
    public static int getVersionCode(Context context) {
        int versionCode = -1;
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            versionCode = packageInfo.versionCode;
        } catch (Exception e) {
            L.e(TAG, e);
        }
        return versionCode;
    }

    /**
     * 获取versionName
     *
     * @param context
     * @return
     * @throws JSONException
     */
    public static String getVersionName(Context context) {
        String versionName = "";
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (Exception e) {
            L.e(TAG, e);
        }
        return versionName;
    }


    /**
     * 指定的activity所属的应用，是否是当前手机的顶级
     *
     * @param context activity界面或者application
     * @return 如果是，返回true；否则返回false
     */
    public static boolean isTopApplication(Context context) {
        if (context == null) {
            return false;
        }

        try {
            String packageName = context.getPackageName();
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
            if (tasksInfo.size() > 0) {
                // 应用程序位于堆栈的顶层
                if (packageName.equals(tasksInfo.get(0).topActivity.getPackageName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            // 什么都不做
            L.e(TAG, e);
        }
        return false;
    }

    public static boolean isTopActivity(Context context, String name) {
        if (context == null || StringUtil.isNullorEmpty(name)) {
            return false;
        }

        try {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
            if (tasksInfo.size() > 0) {
                // 应用程序位于堆栈的顶层
                if (tasksInfo.get(0).topActivity.getClassName().contains(name)) {
                    return true;
                }
            }
        } catch (Exception e) {
            // 什么都不做
            L.e(TAG, e);
        }
        return false;
    }

    /**
     * 指定的activity所属的应用，是否在运行
     *
     * @param context
     * @return
     */
    public static boolean isApplicationRunning(Context context) {
        if (context == null) {
            return false;
        }

        try {
            String packageName = context.getPackageName();
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(10);
            for (int i = 0; i < tasksInfo.size(); i++) {
                if (packageName.equals(tasksInfo.get(i).topActivity.getPackageName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            // 什么都不做
            L.e(TAG, e);
        }
        return false;
    }

    /**
     * 读取manifest.xml中application标签下的配置项，如果不存在，则返回空字符串
     *
     * @param key 键名
     * @return 返回字符串
     */
    public static String getConfigString(Context context, String key) {
        String val = "";
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
            val = appInfo.metaData.getString(key);
            if (val == null) {
                L.e(TAG, "please set config value for " + key + " in manifest.xml first");
            }
        } catch (Exception e) {
            L.e(TAG, e);
        }
        return val;
    }

    public static boolean hasInstalledApp(Context context, String packagename) {
        if (StringUtil.isNullorEmpty(packagename)) {
            return false;
        }
        PackageManager packageMgr = context.getPackageManager();
        List<PackageInfo> list = packageMgr.getInstalledPackages(0);
        for (int i = 0; i < list.size(); i++) {
            PackageInfo info = list.get(i);
            String temp = info.packageName;
            if (temp.equals(packagename)) {
                return true;
            }
        }
        return false;
    }

    public static void openApp(Context context, String packageName) {
        if (StringUtil.isNullorEmpty(packageName)) {
            return;
        }
        try {
            context.startActivity(context.getPackageManager().getLaunchIntentForPackage(packageName));
        } catch (Exception e) {
            L.e(TAG, e);
        }
    }


    /**
     * 读取manifest.xml中application标签下的配置项，如果不存在，则返回空字符串
     *
     * @param key 键名
     * @return 返回字符串
     */
    public static int getConfigInt(Context context, String key) {
        int val = -1;
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
            val = appInfo.metaData.getInt(key);
            if (val == -1) {
                L.e(TAG, "please set config value for " + key + " in manifest.xml first");
            }
        } catch (Exception e) {
            L.e(TAG, e);
        }
        return val;
    }

    /**
     *
     */
    public static void startInstallAPK(Context mContext, File file) {
        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }


    public static String getSign(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
            String sign = signatureMD5(info.signatures);
            sign = sign.toUpperCase();
            L.d(TAG, sign);
            return sign;
        } catch (Exception e) {
            L.e(TAG, e);
        }
        return null;
    }


    public static String signatureMD5(Signature[] signatures) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            if (signatures != null) {
                for (Signature s : signatures)
                    digest.update(s.toByteArray());
            }
            return StringUtil.toHexString(digest.digest());
        } catch (Exception e) {
            L.e(TAG, e);
            return "";
        }
    }

    /**
     * @param context 上下文
     * @param key     权限关键字
     * @return 是否有权限
     */
    public static boolean checkPermission(Context context, String key) {
        PackageManager packageManager = context.getPackageManager();
        return packageManager.checkPermission(key, context.getPackageName()) == PackageManager.PERMISSION_GRANTED;
    }
}
